// const cheerio = require('cheerio')
const puppeteer = require('puppeteer')
const fs = require('fs')
const path = require('path')
const url = 'http://home.c20.org.cn/mooc/index.php?m=content&c=index&a=lists&catid=375'

async function run(params) {
  //打开一个浏览器
  const browser = await puppeteer.launch({
    headless: false
  })

  // 打开一个页面
  const page = await browser.newPage()
  await page.goto(url)

  const result = page.evaluate(() => {
    if (window.data_tree1) {
      return window.data_tree1
    }
  })

  result.then(data => {
    // 将原始数据写入到文件中
    fs.writeFile(__dirname + '/data/origin.js', 'let data = ' + JSON.stringify(data), err => {
      if (!err) console.log('原始数据写入成功！')
    })

    filter(data)

    let back = JSON.parse(JSON.stringify(data))
    filter2(back)

    // 将过滤后数据写入到文件中
    fs.writeFile(__dirname + '/data/data.js', 'let data = ' + JSON.stringify(back), err => {
      if (!err) console.log('过滤后数据写入成功！')
    })
  })
}

function filter(arr) {
  arr.forEach(item => {
    if (item) {
      item.id = item.catId
      item.name = item.text
    }
    if (item.nodes) {
      item.children = item.nodes
      filter(item.children)
    }
  })
}

function filter2(arr) {
  arr.forEach(item => {
    if (item) {
      delete item.catId
      delete item.text
      delete item.href
      delete item.nodes
      delete item.selectable
      delete item.tags
    }
    if (item.children) {
      filter2(item.children)
    }
  })
}

run()
